home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 17385 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  70 lines

  1. Path: unisql.unisql.com!news
  2. From: Ed Hill <edhill@unisql.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: casting w/ virtual base classes
  5. Date: Mon, 15 Apr 1996 12:17:13 -0500
  6. Organization: UniSQL, Inc., Austin, Texas, USA
  7. Message-ID: <31728499.6201DD56@unisql.com>
  8. NNTP-Posting-Host: mazda.unisql.com
  9. Mime-Version: 1.0
  10. Content-Type: text/plain; charset=us-ascii
  11. Content-Transfer-Encoding: 7bit
  12. X-Mailer: Mozilla 2.01 (X11; I; SunOS 4.1.3_U1 sun4c)
  13.  
  14. I have the following class hierarchy
  15.  
  16. class Derived : public virtual Base {...};
  17.  
  18. Suppose there is a function foo that returns a pointer to a virtual
  19. base class.
  20.  
  21.     Base* foo(void) {...}
  22.  
  23. Now, in my program I have a variable declared as a pointer to Derived.
  24.  
  25.     int main() {
  26.         Derived *dp;
  27.         ...
  28.         exit 0;
  29.     }
  30.  
  31. Book Explanation:
  32. =================
  33. In a virtual derivation, the derived class object contains the derived
  34. part and a pointer to the virtual base part. The virtual base class is
  35. not contained within the derived class object.
  36. ==================
  37.  
  38. My compiler does not allow either of the two following statements:
  39.  
  40.     Derived *dp1 = foo();
  41.     Derived    *dp2 = (Derived *) foo();
  42.  
  43. error: cast: Base* ->derived dp2*; Base is virtual base
  44.  
  45. Ok, fine...
  46.  
  47. However, the following compiles:
  48.  
  49.     Derived *dp = (Derived *) (void *) foo();
  50.  
  51. Then, I'm able to access members of Derived and get correct data,
  52. remember foo() returns a pointer to a virtual base.
  53.  
  54.     dp->num; // for example
  55.  
  56. ===
  57. Q1: Is the double cast legal? Why? / Why not?
  58. Q2: How is it possible when from the book explanation, virtual base
  59.     is in a different address space and pointed to from the derived
  60.     class object.
  61. -- 
  62. <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>
  63.  
  64. Ed Hill
  65. Technical Services Consultant                  /\\\
  66. Object-Relational Database Technologies        \///  UniSQL, Inc.
  67. -----------------------------------------------------------------
  68. EMAIL: edhill@unisql.com           
  69. WWW: http://www.unisql.com
  70.